<template>
	<view class="in-review" v-if="shopInfo.status === 0">
		<view class="iconfont icon-zanwuxinxi1"></view>
		<view class="message">店铺正在审核中...</view>
	</view>
	<view class="wrap" v-else>
		<view class="cell">
			<text class="label require">店铺基本信息</text>
			<!-- <button hover-class :disabled="!shopInfo.shopName || !shopInfo.description || !shopInfo.province || !shopInfo.address" @click="tempSave">保存</button> -->
		</view>
		<view class="cell">
			<text class="label">店铺名称</text>
			<input type="text" maxlength="15" :value="shopInfo.shopName" data-name="shopName" @input="onTextInput" placeholder="请输入店铺名称"
			 placeholder-class="placeholder" />
		</view>
		<view class="cell">
			<text class="label">店铺简介</text>
		</view>
		<textarea :value="shopInfo.description" maxlength="80" data-name="description" @input="onTextInput" placeholder="请输入店铺简介***"
		 placeholder-class="placeholder" />
		<view class="cell">
       <text class="label">店铺地址</text>
       <picker class="value" mode="region" @change="onRegionChange">{{shopInfo.province ? (shopInfo.province + '-' + shopInfo.city + '-' + shopInfo.district) : '选择地址'}}</picker>
       <text class="iconfont icon-xiangyou"></text>
     </view>
     <textarea :value="shopInfo.address" data-name="address" @input="onTextInput" placeholder="请输入详细地址" maxlength="100" placeholder-class="placeholder"/>
     <view class="cell upload-cell">
       <text class="label">店铺图片</text>
       <view class="upload">
         <image mode="aspectFill" :src="shopInfo.logo" @click="uploadImg"></image>
       </view>
     </view>
	 <view class="cell" v-if="!shopInfo.id">
	   <text class="label">服务类型(选择后不可更改)</text>
	   <picker :range="serviceType" @change="onServiceTypeChange">
	     <view>{{serviceType[serviceIndex] || "请选择服务类型"}}</view>
	   </picker>
	  <text class="iconfont icon-xiangyou"></text>
	 </view>
	 
	 <view class="cell top-line"  v-if="serviceIndex == 1">
	   <text class="label">服务类目</text>
	   <picker :range="serviceCategory" range-key="name" @change="onServiceCategoryChange">
	     <view>{{serviceCategoryStr || "请选择服务类目"}}</view>
	   </picker>
	  <text class="iconfont icon-xiangyou"></text>
	 </view>
	 
     <view class="cell"  v-if="serviceIndex == 0">
       <text class="label">店铺类型</text>
       <picker mode="multiSelector" :range="shopTypes" @change="onMultiSelectorChange" @columnchange="onColumnChange">
         <view>{{shopTypeStr}}</view>
       </picker>
      <text class="iconfont icon-xiangyou"></text>
     </view>
     
     <view class="cell top-line">
       <text class="label require">申请人基本信息</text>
       <!-- <button hover-class="" :disabled="!shopInfo.bossName || !shopInfo.bossPhone || !shopInfo.bossIdcardNum">保存</button> -->
     </view>
     <view class="cell">
       <text class="label">姓名</text>
       <input type="text" :value="shopInfo.bossName" data-name="bossName" @input="onTextInput" maxlength="5" placeholder="请输入真实姓名" placeholder-class="placeholder" />
     </view>
     <view class="cell">
       <text class="label">手机号</text>
       <input type="number" :value="shopInfo.bossPhone" data-name="bossPhone" @input="onTextInput" placeholder="请输入11位手机号" placeholder-class="placeholder" />
     </view>
     <view class="cell" v-if="false">
       <text class="label">验证码</text>
       <input type="number" value="" maxlength="6" placeholder="请输入验证码" placeholder-class="placeholder" />
       <button hover-class>发送验证码</button>
     </view>
     <view class="cell">
       <text class="label">身份证号</text>
       <input type="text" :value="shopInfo.bossIdcardNum" data-name="bossIdcardNum" @input="onTextInput" placeholder="请输入合法身份证号" placeholder-class="placeholder" />
     </view>
     <button class="submit" hover-class="" :disabled="submitDisabled" @click="save">{{shopInfo.id ? '保存信息' : '申请店铺'}}</button>
<!--     <view class="modal">
       <view class="shop-types">
         <uni-collapse>
           <uni-collapse-item :title="item.title" v-for="(item, i) in shopTypes_">
             <text></text>
             <view class="type-item" v-for="(type, j) in item.list" @click.stop="onSelectType(i, j, type.id)">{{type.title}}</view>
           </uni-collapse-item>
         </uni-collapse>
       </view>
     </view> -->
	</view>
</template>

<script>
  import {utils} from '../../utils/index.js'
  import {Shop} from '../../apis/index.js'
  import uniCollapse from '@/components/uni-collapse/uni-collapse.vue'
  import uniCollapseItem from '@/components/uni-collapse-item/uni-collapse-item.vue'
  
	export default {
    components: {uniCollapse,uniCollapseItem},
		data() {
			return {
				tempStr: '',
				mode: 0, // 0 新建店铺 1 修改店铺信息
				shopTypeStr: '请选择店铺类型',
				isLoading: false,
				submitDisabled: true,
				shopTypes: [[], []],
				shopTypes_: [],
				serviceType: ['普通店铺', '服务型店铺'],
				serviceIndex: -1,
				serviceCategory: [],
				serviceCategoryStr: '',
				serviceCategoryIndex: -1,
				shopInfo: {
				  userId: '',
				  shopName: '',
				  description: '',
				  province: '',
				  city: '',
				  district: '',
				  address: '',
				  logo: '123',
				  bossName: '',
				  bossPhone: '',
				  bossIdcardNum: ''
				},
			}
		},
    onLoad () {
      let userInfo = uni.getStorageSync('userInfo')
      this.shopInfo.userId = userInfo.id
      console.log('自动执行')
      Promise.all([getShopByUserId.call(this), getShopTypes.call(this), getServiceCategoryList.call(this)]).then(([res1, res2, res3]) => {
        console.log('全部获取数据成功', res1, res2, res3)
        let typeStr = '请选择店铺类型'
        // 计算店铺类型
        res2.data.body.map(item => {
          if (res1.data.body && res1.data.body.typeId === item.id) typeStr = item.title
          item.list.length && item.list.map(type => {
            if (res1.data.body && res1.data.body.typeId === type.id) typeStr = `${item.title}-${type.title}`
          })
          this.shopTypeStr = typeStr
        })
		this.serviceCategory = res3.data.body
		try{
			this.serviceCategoryIndex = res3.data.body.map(item => item.id).indexOf(res1.data.body.serviceId)
			this.serviceCategoryStr = this.serviceCategory[this.serviceCategoryIndex].name
		}catch(e){
			//TODO handle the exception
		}
      })
      // 获取地理位置坐标
      uni.getLocation({
          type: 'wgs84',
          success: function (res) {
              console.log('当前位置的经度：' + res.longitude);
              console.log('当前位置的纬度：' + res.latitude);
          },
          fail: function (err) {
            console.error('获取地理位置失败')
            console.error(err)
          }
      })
    },
		methods: {
			onTextInput (e) {
        this.tempStr = e.detail.value
        this.shopInfo[e.currentTarget.dataset.name] = e.detail.value.trim()
        setSubmitDisabled.call(this)
      },
      onRegionChange (e) {
        let [province, city, district] = e.detail.value
        this.tempStr = city
        this.shopInfo.province = province
        this.shopInfo.city = city
        this.shopInfo.district = district
        setSubmitDisabled.call(this)
      },
      uploadImg () {
        utils.uploadImage({
          count: 1
        }).then(res => {
          console.log('上传成功', res)
          this.shopInfo.logo = `https://qiucc.com/${res.body.name}`
        }, err => {
          console.error('上传图片失败', err)
        })
      },
      save () {
        if (this.isLoading) return 
        let msg = validateForm.call(this)
        if (msg) {
          utils.wxToast(msg)
          return
        }
        this.isLoading = true
        utils.wxLoading()
        const userInfo = uni.getStorageSync('userInfo')
        let funcName = this.shopInfo.id ? 'updateShop' : 'addShop'
        this.shopInfo.userId = userInfo.id
		this.shopInfo.serviceId = this.serviceCategory[this.serviceCategoryIndex].id
		this.shopInfo.serviceType = + this.serviceIndex + 1
		
        Shop[funcName]({
          data: {
            form: this.shopInfo
          }
        }).then(res => {
          this.isLoading = false
          uni.hideLoading()
          utils.wxToastSuccess('操作成功').then(() => {
            uni.redirectTo({
              url: '/pages/goodsManage/goodsManage'
            })
          })
        }, err => {
          this.isLoading = false
          uni.hideLoading()
          console.error('操作失败', err)
        })
      },
      onMultiSelectorChange (e) {
         const [parentIndex=0, index=0] = e.detail.value
         this.shopTypeStr = `${this.shopTypes_[parentIndex].title}-${this.shopTypes_[parentIndex].list[index].title}`
         this.tempStr = this.shopTypes_[parentIndex].list[index].id
         this.shopInfo.typeId = this.tempStr
      },
      onColumnChange (e) {
        const {column, value} = e.detail
        if (column === 0) {
          let shopTypes = this.shopTypes
          
          shopTypes[1] = this.shopTypes_[value].list.map(item => item.title)
          console.log(shopTypes)
          this.shopTypes = shopTypes
          this.$mp.page.setData({
            shopTypes
          })
        }
      },
	  onServiceTypeChange (e) {
		  this.serviceIndex = e.detail.value
	  },
	  onServiceCategoryChange (e) {
		  this.serviceCategoryIndex = e.detail.value
		  this.serviceCategoryStr = this.serviceCategory[e.detail.value].name
	  },
      onSelectType (i, j, id) {
      }
	}
}
  function validateForm () {
    let {bossPhone, bossIdcardNum} = this.shopInfo
    let idCardReg1 = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(bossIdcardNum)
    let idCardReg2 = /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/.test(bossIdcardNum)
    if(!(/^1[3456789]\d{9}$/.test(bossPhone))) return '手机号格式错误'
    if (!(idCardReg1 || idCardReg2)) return '身份证号格式错误'
  }
  
  function getShopByUserId () {
    const userInfo = uni.getStorageSync('userInfo')
    if (!userInfo.id) return
    utils.wxLoading()
    return new Promise((resolve, reject) => {
      Shop.getUserShopDetail({
        data: {
          query: {
            id: userInfo.id
          }
        }
      }).then(res => {
        uni.hideLoading()
        console.log('获取店铺信息成功')
        console.log(res)
        if (res.data.code === 200) {
          this.shopInfo = res.data.body || {}
          if (!res.data.body) return
          this.serviceIndex = res.data.body.serviceType - 1
          this.serviceCategoryIndex = res.data.body.serviceId
          setSubmitDisabled.call(this)
          resolve(res)
        } else {
          reject(res)
          utils.wxToast('获取信息失败')
        }
      }, err => {
        uni.hideLoading()
        reject(err)
        console.error(err)
      })
    })
  }
  // 设置保存按钮是否禁用
  function setSubmitDisabled () {
    this.submitDisabled = !(this.shopInfo.shopName
      && this.shopInfo.description
      && this.shopInfo.province
      && this.shopInfo.address
      && this.shopInfo.bossName
      && this.shopInfo.bossPhone
      && this.shopInfo.bossIdcardNum
      )
  }
  
  function getShopTypes () {
    return new Promise((resolve, reject) => {
      Shop.getShopTypes({
        data: {
          request: {},
          pagination: {},
          form: {}
        }
      }).then(res => {
        let types = [[], []]
        types[0] = res.data.body.map(item => item.title)
        types[1] = res.data.body[0].list.map(item => item.title)
        this.shopTypes = types
        this.shopTypes_ = res.data.body
        resolve(res)
      }, reject)
    })
  }
  /**
   * 获取服务类目列表
   */
  function getServiceCategoryList () {
    return new Promise((resolve, reject) => {
      Shop.getShopServices().then(res => {
        this.serviceCategory = res.data.body
        resolve(res)
      })
    })
  }
</script>

<style lang="scss">
page {
  background-color: #EFEFEF;
}
button {
  background-color: #FF4A4A;
  font-size: 28rpx;
  color: #FFFFFF;
  height: 60rpx;
  line-height: 60rpx;
  // width: 140rpx;
  margin: unset;
  &::after {
    border-radius: unset;
  }
  &.submit {
    
  }
}
.cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  box-sizing: border-box;
  padding: 0 20rpx;
  margin-top: 1rpx;
  min-height: 88rpx;
  line-height: 88rpx;
  background-color: #FFFFFF;
  margin-top: 1rpx;
  
  .label {
    font-size: 28rpx;
    box-sizing: border-box;
    padding-right: 10rpx;
    &.require::before {
      content: "*";
      color: #F01919;
    }
  }
  input {
    text-align: right;
  }
  .placeholder {
    color: #888888;
  }
  .value {
    flex: 1;
  }
  .upload {
    width: 120rpx;
    height: 120rpx;
    image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
      background-color: #EFEFEF;
    }
  }
  &.upload-cell {
    padding: 20rpx;
    justify-content: unset;
    margin-bottom: 2rpx;
  }
  picker {
    flex: 1;
    text-align: right;
  }
}
textarea {
  width: 100%;
  height: 160rpx;
  box-sizing: border-box;
  padding: 20rpx  20rpx;
  line-height: 1.5;
  margin-top: 1rpx;
  font-size: 28rpx;
  background-color: #FFFFFF;
}
.top-line {
  margin-top: 20rpx;
}
.submit {
  width: 690rpx;
  height: 80rpx;
  background-color: #FF4A4A;
  line-height: 80rpx;
  margin: 40rpx auto;
}
.in-review {
  padding-top: 200rpx;
  .iconfont {
    text-align: center;
    font-size: 160rpx;
    color: #999999;
  }
  .message {
    text-align: center;
    color: #999999;
    padding-top: 50rpx;
  }
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba($color: #000000, $alpha: 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
}
.shop-types {
  width: 690rpx;
  height: 80vh;
  background-color: #FFF;
  overflow-y: scroll;
  box-sizing: border-box;
  padding: 30rpx 0;
  .type-item {
    font-size: 28rpx;
    font-size: 1.5;
    padding: 20rpx;
    border-bottom: #EFEFEF 1rpx solid;
    padding-left: 50rpx;
  }
}
</style>
